package com.jiyinit.web.core.common.token;

import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.core.framework.base.util.MD5Util;
import com.jiyinit.web.core.business.controller.LoginController;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.Md5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

import static com.alibaba.druid.util.Utils.md5;

/**
 * Created by lr on 2017/11/28.
 */
public class Token {


    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Token.class);
    public static String createToken(TabCoreUserEntity user){
        return MD5Util.MD5Encode(user.getLoginName()+ new Date());
    }

    public static Map<String, String> getQunarSign(String tag, String params){
        Map<String, String> paramMap = new HashMap();
        try {
            String QUNAR_TOKEN = (String) PropertyPlaceholderConfigurer.getContextProperty("QUNAR_TOKEN");
            String QUNAR_KEY = (String) PropertyPlaceholderConfigurer.getContextProperty("QUNAR_KEY");
            String createTime = String.valueOf(new Date().getTime());
            List<String> requestParams = new ArrayList<>();
            requestParams.add("tag=" + tag);
            requestParams.add("params=" + params);
            requestParams.add("key=" + QUNAR_KEY);
            requestParams.add("token=" + QUNAR_TOKEN);
            requestParams.add("createTime=" + createTime);

            Collections.sort(requestParams);

            StringBuilder sb = new StringBuilder();
            for (String param : requestParams) {
                sb.append(param);
            }
            String beforeMd5Str = sb.toString();
            String signqunar = Md5Util.encode(beforeMd5Str);
            String signJiyin = MD5Util.MD5Encode(beforeMd5Str);
            String sign = md5(beforeMd5Str); //加密有问题 不采用该方式
            LogUtil.info(LOGGER, "before md5 beforeMd5Str={}", beforeMd5Str);
            LogUtil.info(LOGGER, "after md5 sign={}",sign);
            LogUtil.info(LOGGER, "after md5 signqunar={}",signqunar);
            LogUtil.info(LOGGER, "after md5 signJiyin={}",signJiyin);

            paramMap.put("sign", signqunar);
            paramMap.put("token", QUNAR_TOKEN);
            paramMap.put("tag", tag);
            paramMap.put("createTime", createTime);
            paramMap.put("params", params);
        }catch (Exception e){
            LogUtil.error(LOGGER, "do sign error:{}", e);
        }
        return paramMap;
    }

}
